﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LambdaToSql.TableStruct
{
    internal class SqLite : LambdaToSql.TableStruct.BaseTable
    {
        /// <summary>
        /// 获取数据库表字段实体
        /// </summary> 
        /// <returns></returns>
        public override Dictionary<string, LambdaToSql.EntityModel.Table> GetDataTable()
        {
            var DbHelper = new LambdaToSql.DbHelper.Factory() { Context = Context }.IDBhelper;

            var DicTable = new Dictionary<string, LambdaToSql.EntityModel.Table>();
            DicTable = new Dictionary<string, LambdaToSql.EntityModel.Table>();
            var Table = DbHelper.ExecuteScalars("select name from sqlite_master where type='table' and name<>'sqlite_sequence' order by name");

            foreach (var name in Table)
            {
                var columns = new List<LambdaToSql.EntityModel.TableColumn>();
                var sdr = DbHelper.ExecuteReader("pragma table_info(" + name + ");");
                while (sdr.Read())
                {
                    columns.Add(new EntityModel.TableColumn()
                    {
                        TableComments = name,
                        TableName = name,
                        Name = sdr["name"].ToString(),
                        Comments = sdr["name"].ToString(),
                        IsNull = sdr["notnull"].ToString() == "1" ? false : true,
                        Type = sdr["type"].ToString(),
                        IsPrimaryKey = sdr["pk"].ToString() == "1" ? true : false,
                        IsIdentity = sdr["pk"].ToString() == "1" ? true : false
                    });
                }
                sdr.Close();

                var table = new EntityModel.Table()
                {
                    Comments = name,
                    Name = name,
                    Columns = columns,
                    PrimaryName = columns.Where(ex => ex.IsPrimaryKey == true).FirstOrDefault().Name
                };
                DicTable.Add(name, table);
            }
            return DicTable;
        }
    }
}
